﻿using System;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Text;

namespace Cgd.Shell.Utilities
{
	/// <summary>
	/// 提供与URL操作相关的功能。
	/// </summary>
	public static class UrlUtility
	{
		static readonly Regex ListRule = new Regex(@"^/list/([^/^\.]*)\.aspx$", RegexOptions.IgnoreCase);
		const string ListTarget = "~/ContentList.aspx?column=$1";
		static readonly Regex RssRule = new Regex(@"^/rss/([^/^\.]*)\.aspx$", RegexOptions.IgnoreCase);
		const string RssTarget = "~/Rss.ashx?column=$1";

		/// <summary>
		/// 进行URL重写。
		/// </summary>
		/// <param name="app">待重写的应用程序。</param>
		public static void RewriteUrl(HttpApplication app)
		{
			int appPathLen = app.Context.Request.ApplicationPath.Length;
			string path = app.Context.Request.Path.Substring(appPathLen);
			if (path[0] != '/')
				path = "/" + path;

			if (ListRule.IsMatch(path))
			{
				app.Context.RewritePath(ListRule.Replace(path, ListTarget));
				return;
			}
			else if (RssRule.IsMatch(path))
			{
				app.Context.RewritePath(RssRule.Replace(path, RssTarget));
				return;
			}
		}

		/// <summary>
		/// 获取站点根路径。
		/// </summary>
		/// <returns>站点根路径，以“/”结尾。</returns>
		public static string GetHostUrl()
		{
			StringBuilder sbUrl = new StringBuilder();
			Uri requrl = HttpContext.Current.Request.Url;

			if (requrl.Port == 80 || requrl.Port == -1)
				sbUrl.AppendFormat("http://{0}", requrl.Host);
			else
				sbUrl.AppendFormat("http://{0}:{1}", requrl.Host, requrl.Port);

			sbUrl.Append(HttpContext.Current.Request.ApplicationPath);

			if (sbUrl[sbUrl.Length - 1] != '/')
				sbUrl.Append("/");

			return sbUrl.ToString();
		}

		/// <summary>
		/// 获取某个路径的完整路径（绝对路径）。
		/// </summary>
		/// <param name="path">相对于应用程序的根路径，前面无需加“~/”。</param>
		/// <returns>path的完整路径。</returns>
		public static string GetFullUrl(string path)
		{
			return GetHostUrl() + path;
		}

		/// <summary>
		/// 获取栏目内容列表URL。
		/// </summary>
		/// <param name="columnName">栏目名称。</param>
		/// <returns></returns>
		public static string GetColumnUrl(string columnName)
		{
			return string.Format("{0}list/{1}.aspx", GetHostUrl(), columnName);
		}

		/// <summary>
		/// 获取栏目RSS地址。
		/// </summary>
		/// <param name="columnName">栏目名称。</param>
		/// <returns></returns>
		public static string GetColumnRssUrl(string columnName)
		{
			return string.Format("{0}rss/{1}.aspx", GetHostUrl(), columnName);
		}
	}

	/// <summary>
	/// 为HTML页面提供没有action属性的form。
	/// </summary>
	public class ActionlessMasterPage : MasterPage
	{
		class MyHtml32TextWriter : Html32TextWriter
		{
			public MyHtml32TextWriter(TextWriter writer)
				: base(writer)
			{
			}

			public override void WriteAttribute(string name, string value, bool fEncode)
			{
				if (string.Compare(name, "action", true) == 0)
					value = HttpContext.Current.Request.RawUrl;

				base.WriteAttribute(name, value, fEncode);
			}
		}

		class MyHtmlTextWriter : HtmlTextWriter
		{
			public MyHtmlTextWriter(TextWriter writer)
				: base(writer)
			{
			}

			public override void WriteAttribute(string name, string value, bool fEncode)
			{
				if (string.Compare(name, "action", true) == 0)
					value = HttpContext.Current.Request.RawUrl;

				base.WriteAttribute(name, value, fEncode);
			}
		}

		protected override void Render(HtmlTextWriter writer)
		{
			if (writer is Html32TextWriter)
				writer = new MyHtml32TextWriter(writer.InnerWriter);
			else
				writer = new MyHtmlTextWriter(writer.InnerWriter);

			base.Render(writer);
		}
	}

	/// <summary>
	/// 用于进行URL重写的模块。
	/// </summary>
	public class UrlRewritingModule : IHttpModule
	{
		public void Dispose()
		{
		}

		public void Init(HttpApplication context)
		{
			context.AuthenticateRequest += (o,e) =>
				UrlUtility.RewriteUrl(context);
		}
	}
}
